package cn.com.common.job.task;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.com.common.config.FileUploadProperties;
import cn.com.common.constants.Constants;
import cn.com.gas.entity.GasDetectionEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.service.GasDetectionService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.nr.entity.NrConcreteEndangerEntity;
import cn.com.nr.entity.NrDetectionEntity;
import cn.com.nr.entity.NrDiggingsEndangerEntity;
import cn.com.nr.service.NrConcreteEndangerService;
import cn.com.nr.service.NrDetectionService;
import cn.com.nr.service.NrDiggingsEndangerService;
import cn.com.system.entity.SysParameterEntity;
import cn.com.system.service.SysParameterService;
import cn.com.thirdparty.entity.ZnGasStation;
import cn.com.thirdparty.mapper.GasDetectionSqlMapper;
import cn.com.thirdparty.mapper.ZnGasStationMapper;
import cn.com.util.DateUtils;
import cn.com.util.HmacSha256Utils;
import cn.com.util.MD5Utils;
import cn.com.util.RestTemplateUtil;
import cn.com.util.TsBqUtils;

/**
 * 定时任务(演示Demo，可删除) testTask为spring bean的名称， 方法名称必须是run
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@Component("gasGetCampicinfoProcessTask")
@DisallowConcurrentExecution
public class GasGetCampicinfoProcessTask {

	@Value("${gasstation.timedTask.gasGetCampicinfoProcessTask}")
	private String gasGetCampicinfoProcessTask;

	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private GasDetectionService gasDetectionService;
	
	@Autowired
	private NrDetectionService nrDetectionService;
	
	@Autowired
	private NrDiggingsEndangerService nrDiggingsEndangerService;
	
	@Autowired
	private NrConcreteEndangerService nrConcreteEndangerService;
	
	@Autowired
	private SysParameterService sysParameterService;
	@Autowired
	private GasDetectionSqlMapper gasDetectionSqlMapper;
	@Value("${gasstation.configCamAIAnalyseGetCampicinfoUrl}")
	private String url;
	@Value("${gasstation.thirdPartyPass}")
	private String pass;
	@Value("${gasstation.thirdPartyUser}")
	private String user;
	
	@Autowired
	private FileUploadProperties fileUploadProperties;
	@Autowired
	private ZnGasStationMapper znGasStationMapper;
	
	public void run(String params) throws Exception {
		logger.debug("gasGetCampicinfoProcessTask定时任务正在执行，参数为：{}", params);
		logger.debug("application参数为gasGetCampicinfoProcessTask：{}", gasGetCampicinfoProcessTask);

		if (gasGetCampicinfoProcessTask.equals(Constants.JOB_STOP)) {
			logger.debug("application配置文件控制不执行gasGetCampicinfoProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasGetCampicinfoProcessTask定时任务");
		}

		Date date = new Date();

		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(GasStationinfoEntity::getIsanalyser, "1");
		
		List<GasStationinfoEntity> list = gasStationinfoService.list(queryWrapper);
		
		for (GasStationinfoEntity gasStationinfo : list) {
			String camid = gasStationinfo.getId();
			// 判断摄像头归属，矿山和油站
			NrDiggingsEndangerEntity diggings = nrDiggingsEndangerService.getById(gasStationinfo.getPid());
			NrConcreteEndangerEntity concrete = nrConcreteEndangerService.getById(gasStationinfo.getPid());
			
			
			String pid = gasStationinfo.getPid();
			GasStationinfoEntity stationinfoEntity = gasStationinfoService.getById(pid);

			Map<String, Object> map = new HashMap<>();
			map.put("api", user);
			// user Zechz2l9PTxMcMJ5N4iCC+6R0OAoys9JBEh59+WBMB8=
			// admin Er3nUTSsBMGIhxikPIQuQDmYpYgaY8gmiBCXpc/d+Ls=
			// String sign= URLEncoder.encode("Zechz2l9PTxMcMJ5N4iCC+6R0OAoys9JBEh59+WBMB8=", "UTF-8");
			// map.put("sign", sign);
			
			Map<String, Object> camerainfo = new HashMap<>();
			camerainfo.put("camid", camid);
			camerainfo.put("mode", 0);
			String camerainfoJson = JSON.toJSONString(camerainfo);
			
			map.put("camerainfo", camerainfoJson);
			
			String str = user + ":" + pass;
			String auth = Base64.getEncoder().encodeToString(str.getBytes());
			
			String domainResponse = RestTemplateUtil.post(url + "?api="+user+"&auth=" + auth, camerainfo);
			
			if (TsBqUtils.isNotNull(domainResponse)) {
				JSONObject json = JSON.parseObject(domainResponse);
				String code = String.valueOf(json.get("code"));
				if ("1".equals(code)) {
					String data = String.valueOf(json.get("data"));
					String msg = String.valueOf(json.get("msg"));

					JSONObject jsonData = JSON.parseObject(data);
					String camidData = String.valueOf(jsonData.get("camid"));
					String piclistData = String.valueOf(jsonData.get("piclist"));

					JSONArray piclistDataJsonArray = JSON.parseArray(piclistData);

					// 遍历JSONArray
					for (int i = 0; i < piclistDataJsonArray.size(); i++) {
						JSONObject jsonObject = piclistDataJsonArray.getJSONObject(i);
						// 获取并打印name字段
						String pic = jsonObject.getString("pic");
						String picTime = jsonObject.getString("pic_time");

						// 处理图片
						String base64Extension = TsBqUtils.getBase64Extension(pic);
						if (TsBqUtils.isNotNull(base64Extension)) {

							String createTime = DateUtils.format(new Date(), DateUtils.DATEPATTERN);
							String imgName = TsBqUtils.getUUID();

							String path = fileUploadProperties.getPath() + createTime + File.separator;
							String url = fileUploadProperties.getUrl() + File.separator + createTime + File.separator
									+ imgName + "." + base64Extension;

							if (TsBqUtils.decodeBase64ToImage(pic, path, imgName + "." + base64Extension)) {
								GasDetectionEntity entity = new GasDetectionEntity();
								entity.setStationId(stationinfoEntity.getId());
								entity.setCamId(camidData);
								entity.setTaxorgcode(stationinfoEntity.getTaxorgcode());
								entity.setPic(url);
								entity.setPicTime(picTime);
								entity.setResult(msg);
								entity.setDeleted(Constants.DELETEED_NOT);
								entity.setCreateId("sys_job");
								entity.setCreateTime(date);
								
								if(TsBqUtils.isNotNull(diggings)||TsBqUtils.isNotNull(concrete)){
									// 矿山 
									NrDetectionEntity nrDetectionEntity = new NrDetectionEntity();
									BeanUtils.copyProperties(entity, nrDetectionEntity);
									nrDetectionService.save(nrDetectionEntity);
								}else{
									gasDetectionService.save(entity);
								}
								
								SysParameterEntity parameterEntity102 = sysParameterService.getById("parameter102");

								try {
									if (TsBqUtils.isNotNull(parameterEntity102)) {
										String parameter102 = parameterEntity102.getParameter();
										if ("Y".equals(parameter102)) {
											LocalDate today = LocalDate.now();
											int year = today.getYear();
											int month = today.getMonthValue();
											String yearStr = year + "";
											String monthStr = "";
											if(month < 10){
												monthStr  = "0" + month;
											}else{
												monthStr  = month + "";
											}
											String thirdPartyId = stationinfoEntity.getThirdPartyId();
											ZnGasStation znGasStation = znGasStationMapper.selectById(thirdPartyId);		
											if(znGasStation.getIsNormal() == 1 && znGasStation.getIsValid() == 1){
												String sql = "INSERT INTO gas_detection_non_1_"+yearStr+"_"+monthStr+" "
														+ "(id, stationId, indexCode, img, createTime) "
														+ " VALUES ('"+TsBqUtils.getUUID()+"', '"+thirdPartyId+"', 'indexCode', '"+url+"', SYSDATE())";
												
												logger.debug("执行sql:" + sql);
												
												gasDetectionSqlMapper.gasDetectionInsertInto(sql);
											}else{
												logger.debug("加油站数据不传IsNormalIsValid:" + znGasStation.getIsNormal() + znGasStation.getIsValid());
											}
										}
									}
								} catch (Exception e) {
									logger.debug("写入gas_detection_non异常:" + e.getMessage());

								}
								

							}else{
								
								GasDetectionEntity entity = new GasDetectionEntity();
								entity.setStationId(stationinfoEntity.getId());
								entity.setCamId(camidData);
								entity.setTaxorgcode(stationinfoEntity.getTaxorgcode());
								entity.setPic(url);
								entity.setPicTime(picTime);
								entity.setResult("图片处理失败decodeBase64ToImage");
								entity.setDeleted(Constants.DELETEED_NOT);
								entity.setCreateId("sys_job");
								entity.setCreateTime(date);
								
								if(TsBqUtils.isNotNull(diggings)||TsBqUtils.isNotNull(concrete)){
									// 矿山 
									NrDetectionEntity nrDetectionEntity = new NrDetectionEntity();
									BeanUtils.copyProperties(nrDetectionEntity, entity);
									nrDetectionService.save(nrDetectionEntity);
								}else{
									gasDetectionService.save(entity);
								}
								
								logger.error("application配置文件控制不执行gasGetCampicinfoProcessTask定时任务,图片处理失败decodeBase64ToImage");
								
							}

						}else{
							GasDetectionEntity entity = new GasDetectionEntity();
							entity.setStationId(stationinfoEntity.getId());
							entity.setCamId(camidData);
							entity.setTaxorgcode(stationinfoEntity.getTaxorgcode());
							entity.setPic(url);
							entity.setPicTime(picTime);
							entity.setResult("图片处理失败base64Extension");
							entity.setDeleted(Constants.DELETEED_NOT);
							entity.setCreateId("sys_job");
							entity.setCreateTime(date);

							if(TsBqUtils.isNotNull(diggings)||TsBqUtils.isNotNull(concrete)){
								// 矿山 
								NrDetectionEntity nrDetectionEntity = new NrDetectionEntity();
								BeanUtils.copyProperties(entity, nrDetectionEntity);
								nrDetectionService.save(nrDetectionEntity);
							}else{
								gasDetectionService.save(entity);
							}
							
							logger.error("application配置文件控制不执行gasGetCampicinfoProcessTask定时任务,图片处理失败base64Extension");
						
						}

					}

				} else {
					String msg = String.valueOf(json.get("msg"));

					GasDetectionEntity entity = new GasDetectionEntity();
					entity.setStationId(stationinfoEntity.getId());
					entity.setCamId(camid);
					entity.setTaxorgcode(stationinfoEntity.getTaxorgcode());
					entity.setPic("");
					entity.setPicTime("");
					entity.setResult(msg);
					entity.setDeleted(Constants.DELETEED_NOT);
					entity.setCreateId("sys_job");
					entity.setCreateTime(date);

					if(TsBqUtils.isNotNull(diggings)||TsBqUtils.isNotNull(concrete)){
						// 矿山 
						NrDetectionEntity nrDetectionEntity = new NrDetectionEntity();
						BeanUtils.copyProperties(nrDetectionEntity, entity);
						nrDetectionService.save(nrDetectionEntity);
					}else{
						gasDetectionService.save(entity);
					}

				}
				
				
			}
		}

	}

	@SuppressWarnings("unused")
	private String sign(String url, Map<String, Object> parameter) throws UnsupportedEncodingException {
		if (!parameter.isEmpty()) {
			url = url + "?";
			for (String key : parameter.keySet()) {
				url = url + key + "=" + parameter.get(key) + "&";
			}
			url = url.substring(0, url.length() - 1);
		}

		String encrypt = MD5Utils.encrypt(pass);
		byte[] hmacSHA256 = HmacSha256Utils.hmacSHA256(url, encrypt);
		byte[] encodedBytes = Base64.getEncoder().encode(hmacSHA256);
		String encodedString = URLEncoder.encode(new String(encodedBytes), "UTF-8");

		return encodedString;
	}
	
	public String removeFirstAndLastChar(String s) {
		if (s.length() <= 2) {
			return ""; // 如果字符串长度小于等于2，则返回空字符串
		}
		String str = s.substring(1, s.length() - 1);
		String replaceAll = str.replaceAll("\\\\", "");
		return replaceAll;

	}
	
}
